﻿using System.Reflection;
using WinRTClient.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using StyleMVVM;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

namespace WinRTClient
{
    sealed partial class App : Application
    {
        public App()
        {
            this.InitializeComponent();
            this.Suspending += OnSuspending;
        }

        protected override async void OnLaunched(LaunchActivatedEventArgs args)
        {
            CreateBootstrapper();

            if (args.PreviousExecutionState == ApplicationExecutionState.Running)
            {
                Window.Current.Activate();
                return;
            }

            var rootFrame = new Frame();

            StyleMVVM.Suspension.SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

            if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
            {
                await StyleMVVM.Suspension.SuspensionManager.RestoreAsync();
            }

            if (rootFrame.Content == null)
            {
                Type navigateType = Bootstrapper.Instance.Container.LocateExportType("StartPage");

                if (navigateType == null)
                {
                    throw new Exception("Could not find start page.");
                }

                if (!rootFrame.Navigate(navigateType))
                {
                    throw new Exception("Failed to create initial page");
                }
            }

            Window.Current.Content = rootFrame;
            Window.Current.Activate();
        }

        private async void OnSuspending(object sender, SuspendingEventArgs e)
        {
            var deferral = e.SuspendingOperation.GetDeferral();
            await StyleMVVM.Suspension.SuspensionManager.SaveAsync();
            deferral.Complete();
        }

        private void CreateBootstrapper()
        {
            if (!Bootstrapper.HasInstance)
            {
                Bootstrapper newBootstrapper = new Bootstrapper();

                newBootstrapper.Container.RegisterAssembly(
                    GetType().GetTypeInfo().Assembly);

                newBootstrapper.Start();
            }
        }
    }
}
